<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 首先循环所有数据  然后判断pid 的值是否符合id
        let arr = [
            { id: 1, pid: null }, // id 为元素的唯一标识，pid：对应的父元素的id
            { id: 2, pid: 1 },
            { id: 3, pid: 1 },
            { id: 4, pid: null },
            { id: 5, pid: 2 },];


        function arrMap1(data, root) {
            // console.log(data,root);
            // 递归方法
            function dealData(id) {
                var node = []
                for (var i = 0; i < data.length; i++) {
                    console.log(data[i]['pid'],id,data[i]['pid'] == id);
                    if (data[i]['pid'] == id) {
                        
                        data[i]['children'] = dealData(data[i]['id'])||null
                        node.push(data[i])
                    }
                }
                if (node.length == 0) {
                    return
                } else {
                    return node
                }
            }
            // 使用根节点
            return dealData(root)
        }
        
        console.log(arrMap1(arr));

        function arrMap(arr) {
            // console.log(arr,'数据');
            function dealData(_item) {

            }

            let newArr = []
            arr.map((item, index) => {
                let { id, pid } = item
                //    console.log(id,pid,'数据');
                let obj = {
                    id,
                    pid,
                    children: []
                }
                if (pid) {
                    let idx = newArr.findIndex(item => item.id == pid)
                    console.log(idx, '不是-1', pid);
                    if (idx != -1) {
                        newArr[idx].children.push(obj)
                    } else {
                        // console.log(pid,'下一个');
                        dealData(item)
                    }

                } else {
                    newArr.push(obj)
                }
            })
            console.log(newArr,'2');
            return newArr
        }

        arrMap(arr)
    </script>
</body>

</html>